package com.sctvcloud.dongqu.ui.activities;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.tracker.GridsumWebDissector;
import com.gridsum.videotracker.entity.VideoInfo;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.NetModeUtil;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.application.Cache;
import com.sctvcloud.dongqu.application.Constances;
import com.sctvcloud.dongqu.base.BaseActivity;
import com.sctvcloud.dongqu.base.BaseCanPlayActivity;
import com.sctvcloud.dongqu.beans.FUsers;
import com.sctvcloud.dongqu.beans.FocusColumn;
import com.sctvcloud.dongqu.beans.NewsItem;
import com.sctvcloud.dongqu.beans.SingleResult;
import com.sctvcloud.dongqu.http.AbsListNetCallback;
import com.sctvcloud.dongqu.http.AbsNetCallBack;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.http.ParamsEditor;
import com.sctvcloud.dongqu.ui.adapter.VideoPlayAdapter;
import com.sctvcloud.dongqu.ui.adapter.holder.VideoPlayHolder;
import com.sctvcloud.dongqu.ui.dialog.NetModeDiaFragment;
import com.sctvcloud.dongqu.ui.utils.SkipUtil;
import com.sctvcloud.dongqu.ui.widget.BasePlayerView;
import com.sctvcloud.dongqu.utils.ListTypeUtils;
import com.sctvcloud.dongqu.utils.UserManager;

import org.xutils.common.util.LogUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.sctvcloud.dongqu.ui.dialog.NetModeDiaFragment.NO_TAG;
import static com.sctvcloud.dongqu.ui.dialog.NetModeDiaFragment.OK_TAG;

/**
 * 热门视频播放列表
 */
public class VideoPlayViewActivity extends BaseCanPlayActivity implements VideoPlayHolder.NewsItemClickListener, VideoPlayHolder.NewsItemTitleClickListener, VideoPlayHolder.NewsItemDoUpClickListener,
        CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, BaseCanPlayActivity.OnPlayerFullClickListener {

    public static final String IS_LIVE = "is_live_data";
    public static final String CHANNEL_URL_KEY = "live_channel_url";
    public static final String PLAYING_URL = "playing_url";
    public static final String JUMP_INTO_INDEX = "jump_into_index";//从外部列表中跳入的位置
    public static final String JUMP_INTO_PAGE_INDEX = "jump_into_page_index";//从外部列表中跳入的页码
    public static final String JUMP_INTO_PAGEALL_INDEX = "jump_into_pageAll_index";//从外部列表中跳入的页码总数
    public static final String CURRENT_TO = "current_to";//跳转到
    public static final int INTO_NEWSINFO = 1;
    public static final String INTO_NEWSINFO_ISDIGG = "info_isDigg";

    //    private static final float MIN_SCALE = 0.75f;
//    private static final float MIN_ALPHA = 0.75f;
//    protected BasePlayerView videoPlayer;
    @BindView(R.id.no_data)
    protected CustomFontTextView noDataView;

    @BindView(R.id.title_top_back)
    protected ImageView back;
    @BindView(R.id.fm_live_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;
    private VideoPlayAdapter adapter;
    private List<NewsItem> newsList = new ArrayList<>();
    private Handler handler;
    private Handler playHandler;
    private int currentToIndex = -1;
    private int lastIndex = 0;
    private int lastLoadMoreIndex = 0;
    private int currentPage = 0;
    private int pageAll = 0;
    private boolean isLoading = false;
    private boolean isCanPlayVideo = true;
    private BasePlayerView playPlayer = null;
    private boolean isLoadDetail = false;
    private String lastChannelId = "";
    private boolean isMute = false;//是否开放声音
    private boolean isNormalScreenShow = true;
    private int selectedToInfoIndex = 0;
    //目标项是否在最后一个可见项之后
    private boolean mShouldScroll;
    //记录目标项位置
    private int mToPosition;
    //    private int loadMoreType = 0;
    private boolean mIsLoadAll = false;

    /**
     * 直播的各栏目:直播, 回顾
     */
    private FocusColumn livingColumn, reviewColumn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lastChannelId = Cache.getInstance().getCurrentChannelId();
        String channelID = Cache.getInstance().getCurrentColumnId("精选", "精选");
        Cache.getInstance().setCurrentChannelId(channelID);
        newsList = new ArrayList<>();
        handler = new Handler();
        currentToIndex = getIntent().getIntExtra(CURRENT_TO, -1);
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_video_play_view);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isCanPlayVideo = true;
        if (isLoadDetail) {
            RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
            View view = manager.findViewByPosition(lastIndex);
            if (null != view) {
                VideoPlayHolder holder = (VideoPlayHolder) recyclerView.getChildViewHolder(view);
                initPlayer(holder.videoPlayer, lastIndex);
                setVideoPlay(holder, lastIndex);
            }
            isLoadDetail = false;
        }
    }

    @Override
    protected void onDestroy() {
        Cache.getInstance().setCurrentChannelId(lastChannelId);
        isCanPlayVideo = false;
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        View lastView = manager.findViewByPosition(lastIndex);
        if (null != lastView) {
            VideoPlayHolder lastHolder = (VideoPlayHolder) recyclerView.getChildViewHolder(lastView);
            lastHolder.pauseVideo();
        }
        if (null != playPlayer) {
            playPlayer.onVideoPause();
        }
        recyclerView.removeAllViews();
        recyclerView = null;
        super.onDestroy();

    }

    private void initView() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
//        refreshLayout.setLoadMoreEnabled(false);
        adapter = new VideoPlayAdapter(this, null);
        adapter.setActivity(this);
        adapter.setDoUpClickListener(this);
        adapter.setNewsItemListener(this);
        adapter.setTitleClickListener(this);
        adapter.setMuteChangeListener(new VideoPlayAdapter.OnMuteChangeListener() {
            @Override
            public void OnMuteChange(boolean isMute) {
                VideoPlayViewActivity.this.isMute = isMute;
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                if (mShouldScroll && RecyclerView.SCROLL_STATE_IDLE == newState) {
                    mShouldScroll = false;
                    smoothMoveToPosition(recyclerView, mToPosition);
                }
                if (isNotScrollStateChanged) {
//                    isNotScrollStateChanged = false;
                    return;
                }
                if (recyclerView.getLayoutManager() != null && RecyclerView.SCROLL_STATE_IDLE == newState) {
                    LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    int topPosition = layoutManager.findFirstVisibleItemPosition();
                    int temp = topPosition;
                    RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();

                    View topView = layoutManager.findViewByPosition(topPosition);
                    VideoPlayHolder holder = null;
                    if (null != topView) {
                        int bottom = topView.getBottom();
                        int height = topView.getHeight();
                        if (bottom < height * 2 / 3) {
                            View view = manager.findViewByPosition(topPosition + 1);
                            if (null != view) {
                                holder = (VideoPlayHolder) recyclerView.getChildViewHolder(view);
                            }
                            temp = topPosition + 1;
                        } else {
                            View view = manager.findViewByPosition(topPosition);
                            if (null != view) {
                                holder = (VideoPlayHolder) recyclerView.getChildViewHolder(view);
                            }
                            temp = topPosition;
                        }
                    }
                    if (temp != lastIndex) {
                        if (null != holder) {
                            final int index = temp;
                            View lastView = manager.findViewByPosition(lastIndex);
                            if (null != lastView) {
                                VideoPlayHolder lastHolder = (VideoPlayHolder) recyclerView.getChildViewHolder(lastView);
                                lastHolder.pauseVideo();
                            }
                            JLog.e("viewplay", "---onScrollStateChanged----setVideoPlay----");
                            initPlayer(holder.videoPlayer, temp);
                            final VideoPlayHolder playHolder = holder;
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    setVideoPlay(playHolder, index);
                                }
                            }, 500);

                            lastIndex = temp;
                        }
                    }
                    smoothMoveToPosition(recyclerView, lastIndex);
                    isNotScrollStateChanged = mIsLoadAll;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (isNotScrolled) {
                    //点击视频时，不触发此处的处理逻辑
//                    isNotScrolled = false;
                    return;
                }
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int topPosition = layoutManager.findFirstVisibleItemPosition();
                int bottomPosition = layoutManager.findLastVisibleItemPosition();
                int temp = topPosition;
                RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                View topView = layoutManager.findViewByPosition(topPosition);
                if (null != topView) {
                    int bottom = topView.getBottom();
                    int height = topView.getHeight();
                    if (bottom < height * 2 / 3) {
                        temp = topPosition + 1;
                    } else {
                        temp = topPosition;
                    }
                }
                if (temp != lastIndex) {
                    View lastView = manager.findViewByPosition(lastIndex);
                    if (null != lastView) {
                        VideoPlayHolder lastHolder = (VideoPlayHolder) recyclerView.getChildViewHolder(lastView);
                        lastHolder.pauseVideo();
                    }
                }
//                if (dy > 0) {
//                    isUp = true;
//                } else {
//                    isUp = false;
//                }
                if (dy > 0 && bottomPosition >= (newsList.size() - 3) && bottomPosition != lastLoadMoreIndex) {
                    //向上滑动到距离列表最后一项还有2条时，加载更多
                    lastLoadMoreIndex = bottomPosition;
                    loadMore(0);
                }
                if (dy > 0) {//向下滚动
                    int visibleItemCount = layoutManager.getChildCount();
                    int totalItemCount = layoutManager.getItemCount();
                    int pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();
                    if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                        mIsLoadAll = true;
//                        handler.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                isNotScrollStateChanged = true;
//                            }
//                        }, 2000);
                    } else {
                        mIsLoadAll = false;
                        isNotScrollStateChanged = false;
                    }
                }else{
                    isNotScrollStateChanged = false;
                }
            }

        });
        recyclerView.setAdapter(adapter);
        initFirstData();//接收外部列表进入数据处理逻辑

        playHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (isCanPlayVideo && !VideoPlayViewActivity.this.isFinishing() && !VideoPlayViewActivity.this.isDestroyed()) {
                    if (msg.what == 0) {
                        if (null != recyclerView) {
                            if (currentToIndex >= 0) {
                                recyclerView.scrollToPosition(currentToIndex);
                                lastIndex = currentToIndex;
                            }
                            RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                            View view = manager.findViewByPosition(lastIndex);
                            if (null != view) {
                                VideoPlayHolder holder = (VideoPlayHolder) recyclerView.getChildViewHolder(view);
                                initPlayer(holder.videoPlayer, lastIndex);
                                setVideoPlay(holder, lastIndex);
                            }
                        }
                    } else if (msg.what == 1) {
                        if (null != recyclerView) {
                            RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                            View view = manager.findViewByPosition(lastIndex);
                            if (null != view) {
                                VideoPlayHolder holder = (VideoPlayHolder) recyclerView.getChildViewHolder(view);
                                initPlayer(holder.videoPlayer, lastIndex);
                                setVideoPlay(holder, lastIndex);
                            }
                        }
                    }
                }
            }
        };
    }

    /**
     * 加载从外部列表进入短视频播放列表的数据逻辑
     */
    private void initFirstData() {
        List<NewsItem> shortVideonList = Cache.getInstance().getShortVideonList();
        final int position = getIntent().getIntExtra(JUMP_INTO_INDEX, 0);
        currentPage = getIntent().getIntExtra(JUMP_INTO_PAGE_INDEX, 0);
        pageAll = getIntent().getIntExtra(JUMP_INTO_PAGEALL_INDEX, 0);
        if (ListUtils.isListValued(shortVideonList)) {
            newsList.clear();
            newsList.addAll(shortVideonList);
            adapter.setData(newsList);
            isNotScrolled = true;
            isNotScrollStateChanged = true;
            if (position < newsList.size()) {
                if (position != -1) {
                    recyclerView.scrollToPosition(position);
                }
            }

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    final RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                    View view = manager.findViewByPosition(position);
                    if (null != view) {
                        final VideoPlayHolder holder = (VideoPlayHolder) recyclerView.getChildViewHolder(view);
                        initPlayer(holder.videoPlayer, position);
                        lastIndex = position;
                        setVideoPlay(holder, position);
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                isNotScrolled = false;
                                isNotScrollStateChanged = false;
                            }
                        }, 1000);
                    }
                }
            }, 500);
            onNetFinish();
            if (position >= (newsList.size() - 3)) {
                //向上滑动到距离列表最后一项还有2条时，加载更多
                lastLoadMoreIndex = position;
                loadMore(0);
            }
        } else {
            refreshLayout.autoRefresh();
        }
    }

    /**
     * 判断当前网络状态，以及之前是否已经提示过了。
     *
     * @return
     */
    private boolean checkNet() {
        if (!Cache.getInstance().isCheckNet() && 1 != NetModeUtil.GetNetype(this)) {
            showNetDialog();
        } else {
            return true;
        }
        return false;
    }

    /**
     * 提示用户网络情况
     */
    private void showNetDialog() {
        if (netModeDiaFragment == null) {
            netModeDiaFragment = new NetModeDiaFragment();
        }
        if (fragmentDialogShowHelper != null && !fragmentDialogShowHelper.isResuming()) {
            return;
        }
        if (!netModeDiaFragment.isAdded()) {
            netModeDiaFragment.setCallBack(netClickBack);
            netModeDiaFragment.show(getSupportFragmentManager(), NET_TAG);
        }
    }

    BaseDialogFragment.ICallBack netClickBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == NO_TAG) {
            } else if (msg.what == OK_TAG) {
                Cache.getInstance().setCheckNet(true);
                setVideoPlay(willHolder, index);
            }
        }
    };
    //记录当前准备播放的数据
    private VideoPlayHolder willHolder;
    private int index;

    /**
     * 开始播放
     *
     * @param holder
     * @param position
     */
    private void setVideoPlay(VideoPlayHolder holder, int position) {
        LogUtil.e("-----VideoPlayHolder position =" + position + "------");
        willHolder = holder;
        index = position;
        if (checkNet() && isCanPlayVideo && !this.isFinishing() && !this.isDestroyed()) {
            playPlayer = holder.videoPlayer;
            holder.playVideo();
            holder.setMute(isMute);
            if (position < newsList.size()) {
                initViewClickData(newsList.get(position).getNewsId());
            }
        }
    }

    /**
     * 初始化播放控件，以实现全屏等功能
     *
     * @param player
     * @param index
     */
    private void initPlayer(BasePlayerView player, int index) {
        if (newsList.size() > index) {
            VideoInfo videoInfo = new VideoInfo("");
            videoInfo.Cdn = "cdn";
            videoInfo.VideoOriginalName = newsList.get(index).getNewsTitle();
            videoInfo.VideoName = newsList.get(index).getNewsTitle();
            videoInfo.VideoUrl = Constances.ST_BASE_URL + newsList.get(index).getNewsMediaUrl();
            videoInfo.extendProperty1 = "四川观察APP_Android";
            videoInfo.extendProperty1 = "";
            videoInfo.extendProperty1 = NetUtils.GetNetName(this);
            videoInfo.setVideoWebChannel("///");
            if (null != player) {
                initVideoPlayer(player, videoInfo, videoInfo.VideoUrl.endsWith("m3u8"), this);
            }
        }
    }


    @Override
    public void onFullClick(boolean isNormal) {
        isNormalScreenShow = isNormal;
    }

    @Override
    public void onBackPressed() {
        if (isNormalScreenShow) {
            isCanPlayVideo = false;

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != recyclerView) {
                        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                        View lastView = manager.findViewByPosition(lastIndex);
                        if (null != lastView) {
                            VideoPlayHolder lastHolder = (VideoPlayHolder) recyclerView.getChildViewHolder(lastView);
                            lastHolder.pauseVideo();
                        }
                        if (null != playPlayer) {
                            playPlayer.onVideoPause();
                        }
                    }
                    VideoPlayViewActivity.super.onBackPressed();
                }
            }, 200);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onPause() {
        isCanPlayVideo = false;
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        View lastView = manager.findViewByPosition(lastIndex);
        if (null != lastView) {
            VideoPlayHolder lastHolder = (VideoPlayHolder) recyclerView.getChildViewHolder(lastView);
            lastHolder.pauseVideo();
        }
        if (null != playPlayer) {
            playPlayer.onVideoPause();
        }
        super.onPause();
    }


    @Override
    public void onLoadMore() {
//        loadMore(1);
        refreshLayout.loadMoreComplete();
    }

    private void loadMore(int type) {
        if (!isLoading) {
            currentPage = currentPage + 1;
            if (currentPage < pageAll) {
//                loadMoreType = type;
//                Toast.makeText(this, "更多视频了", Toast.LENGTH_LONG).show();
                getHotVideoList(currentPage);
            } else {
                onNetFinish();
                if (type == 1) {
                    Toast.makeText(this, "没有更多视频了", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    private void refreshDataPause() {
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        View lastView = manager.findViewByPosition(lastIndex);
        if (null != lastView) {
            VideoPlayHolder lastHolder = (VideoPlayHolder) recyclerView.getChildViewHolder(lastView);
            lastHolder.pauseVideo();
        }
    }

    private void onNetFinish() {
        refreshLayout.refreshComplete();
        refreshLayout.loadMoreComplete();
        isLoading = false;
    }

    @Override
    public void onRefresh() {
        int currentPage = 0;
        getHotVideoList(currentPage);
    }

    /**
     * 请求短视频的数据
     */
    private void getHotVideoList(int calledPage) {
//        String url = Cache.getInstance().getHotVideoUrl();
//        if (TextUtils.isEmpty(url)) {
//            Toast.makeText(this, "数据错误", Toast.LENGTH_LONG).show();
//            refreshLayout.setVisibility(View.GONE);
//            noDataView.setVisibility(View.VISIBLE);
//            return;
//        }
        isLoading = true;
        Map<String, Object> param = new ArrayMap<>();
        param.put("siteNumber", Constances.SITE_ID);
        param.put("page", calledPage);
        param.put("size", 10);
        FUsers user = UserManager.getInstance().getUser();
        if (user != null && !TextUtils.isEmpty(user.getUserId())) {
            param.put("userId", user.getUserId());
        } else {
            param.put("userId", "");
        }
        NetUtils.getNetAdapter().getShortVideos(getOwnerName(), param, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem(), calledPage) {

            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (ListUtils.isListValued(newsItems)) {
                    pageAll = getPageResponse().getData().getPageAll();
                    currentPage = getPageResponse().getData().getPageIndex();
                    if (currentPage == 0) {
                        refreshDataPause();
//                        for (int i = 0; i < newsItems.size(); i++) {
//                            newsItems.get(i).setNewsMediaUrl(newsItems.get(6).getNewsMediaUrl());
//                        }
                        newsList.clear();
                        newsList.addAll(newsItems);
                        adapter.setData(newsItems);

                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Message msg = new Message();
                                msg.what = 0;
                                playHandler.handleMessage(msg);
                            }
                        }, 1000);
                    } else {
                        newsList.addAll(newsItems);
                        adapter.addData(newsItems);
////                        if(loadMoreType == 1) {
//                            //只有主动上拉翻页才刷新播放。
//                            handler.postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//
//                                    Message msg = new Message();
//                                    msg.what = 1;
//                                    playHandler.handleMessage(msg);
//                                }
//
//                            }, 1000);
////                        }
                    }

                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                refreshLayout.setVisibility(View.GONE);
                noDataView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }

        });
//        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), url, calledPage, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem(), calledPage) {
//            @Override
//            public void onSuc(List<NewsItem> newsItems) {
//                if (ListUtils.isListValued(newsItems)) {
//                    pageAll = getPageResponse().getData().getPageAll();
//                    currentPage = getPageResponse().getData().getPageIndex();
//                    if (currentPage == 0) {
////                        for (int i = 0; i < newsItems.size(); i++) {
////                            newsItems.get(i).setNewsMediaUrl(newsItems.get(6).getNewsMediaUrl());
////                        }
//                        newsList = newsItems;
//                        adapter.setData(newsItems);
//
//                        handler.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                Message msg = new Message();
//                                msg.what = 0;
//                                playHandler.handleMessage(msg);
//                            }
//                        }, 1000);
//                    } else {
//                        newsList.addAll(newsItems);
//                        adapter.addData(newsItems);
//                        handler.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                Message msg = new Message();
//                                msg.what = 1;
//                                playHandler.handleMessage(msg);
//                            }
//                        }, 1000);
//                    }
//
//                }
//            }
//
//            @Override
//            public void onError(Throwable ex, String errorMsg) {
//                super.onError(ex, errorMsg);
//                refreshLayout.setVisibility(View.GONE);
//                noDataView.setVisibility(View.VISIBLE);
//            }
//
//            @Override
//            public void onEnd() {
//                super.onEnd();
//                refreshLayout.refreshComplete();
//                refreshLayout.loadMoreComplete();
//                isLoading = false;
//            }
//        });


    }

    /**
     * 增加点击
     *
     * @param newID
     */
    private void initViewClickData(final String newID) {
        ArrayMap<String, Object> p = new ArrayMap<>();
        p.put("id", newID);
        p.put("type", 0);//type（0.新闻 1.直播)
        NetUtils.getNetAdapter().addNewOrLivingClick(getOwnerName(), p, new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onSuc(SingleResult vo) {
                JLog.e("initViewClickData", newID + "  video click  " + vo.isSuccess());
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }
        });


    }

    @Override
    public void OnItemDoUpClick(int position, String newsId) {
        //点赞按钮回调
        shortVideoDoUp(position, newsId);
    }

    private VideoPlayHolder lastHolder = null;

    /**
     * 短视频点赞
     */
    private void shortVideoDoUp(final int mToPosition, final String newsId) {
        if (!TextUtils.isEmpty(newsId)) {
            if (UserManager.isLoginS()) {
                RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                View lastView = manager.findViewByPosition(mToPosition);

                if (null != lastView) {
                    lastHolder = (VideoPlayHolder) recyclerView.getChildViewHolder(lastView);
                    if (null != lastHolder) {
                        lastHolder.doUp.setDrawableEnlarge();
                    }
                }

                ParamsEditor pe = new ParamsEditor();
//        HashMap<String, Object> param = new HashMap<>();
                pe.put("dynamicId", newsId);
                pe.put("fType", 3);//1 主播 2报料 3新闻(短视频) 4 直播
//        pe.put("token", UserManager.getInstance().getToken());
                pe.put("userId", UserManager.getInstance().getUser().getUserId());

                NetUtils.getNetAdapter().doUpForDynamics(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<SingleResult>(SingleResult.class) {
                    @Override
                    public void onSuc(SingleResult singleResult) {
                        if (singleResult.isSuccess()) {
                            SkipUtil.skipToAddUserOperate(VideoPlayViewActivity.this, getOwnerName(), 13, 4, "短视频点赞/取消点赞", newsId, Cache.getInstance().getCurrentChannelId());
                            if (null != newsList && newsList.size() > mToPosition) {
                                RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                                View lastView = manager.findViewByPosition(mToPosition);
                                VideoPlayHolder lastHolder = null;
                                if (null != lastView) {
                                    lastHolder = (VideoPlayHolder) recyclerView.getChildViewHolder(lastView);
                                }
                                NewsItem news = newsList.get(mToPosition);
                                if (news.isDigg()) {
                                    newsList.get(mToPosition).setCountDigg(news.getCountDigg() - 1);
                                    if (null != lastHolder) {
                                        Drawable drawable = VideoPlayViewActivity.this.getResources().getDrawable(R.mipmap.icon_compere_btn_white);
                                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                        lastHolder.doUp.setDrawables(drawable, null, null, null);
                                        lastHolder.doUp.setTextColor(VideoPlayViewActivity.this.getResources().getColor(R.color.colorOpinionSelectNo));
                                        lastHolder.doUp.setText("" + newsList.get(mToPosition).getCountDigg());
                                    }

                                } else {
                                    newsList.get(mToPosition).setCountDigg(news.getCountDigg() + 1);
                                    if (null != lastHolder) {
                                        Drawable drawable = VideoPlayViewActivity.this.getResources().getDrawable(R.mipmap.icon_compere_btn_press);
                                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                        lastHolder.doUp.setDrawables(drawable, null, null, null);
                                        lastHolder.doUp.setTextColor(VideoPlayViewActivity.this.getResources().getColor(R.color.colorTxRedMain_));
                                        lastHolder.doUp.setText("" + newsList.get(mToPosition).getCountDigg());
                                    }
                                    addInvitation(Constances.ADD_INTEGRAL_DOUP, false);
                                }
                                newsList.get(mToPosition).setDigg(!news.isDigg());
                                adapter.updateData(newsList);

                            }
                        }
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg, int netCode) {
                        super.onError(ex, errorMsg, netCode);
                    }
                });

            } else {
                toLogin();
            }
        }
    }

    private boolean isNotScrolled = false;
    private boolean isNotScrollStateChanged = false;

    @Override
    public void OnItemClick(final int position) {
        isNotScrolled = true;
        isNotScrollStateChanged = true;
        final RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        View lastView = manager.findViewByPosition(lastIndex);
        if (null != lastView) {
            VideoPlayHolder lastHolder = (VideoPlayHolder) recyclerView.getChildViewHolder(lastView);
            lastHolder.pauseVideo();
        }
        if (position < newsList.size()) {
            if (position != -1) {
                smoothMoveToPosition(recyclerView, position);
            } else {
                smoothMoveToPosition(recyclerView, position + 1);
            }
        }
//        recyclerView.scrollToPosition(position);
        View view = manager.findViewByPosition(position);
        if (null != view) {
            final VideoPlayHolder holder = (VideoPlayHolder) recyclerView.getChildViewHolder(view);
            initPlayer(holder.videoPlayer, position);
            lastIndex = position;
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    setVideoPlay(holder, position);
                }
            }, 500);
        }

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                isNotScrolled = false;
                isNotScrollStateChanged = false;
            }
        }, 500);
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        int bottomPosition = layoutManager.findLastVisibleItemPosition();
        if (bottomPosition >= (newsList.size() - 3) && bottomPosition != lastLoadMoreIndex) {
            //向上滑动到距离列表最后一项还有2条时，加载更多
            lastLoadMoreIndex = bottomPosition;
            loadMore(0);
        }
    }

    @Override
    public void OnItemTitleClick(int mToPosition, NewsItem item) {
        selectedToInfoIndex = mToPosition;
//        String title = item.getNewsTitle();
//        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
//        pairs.add(new Pair<>("页面", "首页"));
//        pairs.add(new Pair<>("栏目", "精选"));
//        pairs.add(new Pair<>("位置", "热门视频"));
//        ArrayList<Pair<String, String>> tempPair = new ArrayList<>();
//        tempPair.addAll(pairs);
//        tempPair.add(new Pair<>("行为类型", "点击"));
////            pairs.add(new Pair<>("行为类型", "点击"));
//
//        GridsumWebDissector.getInstance().trackEvent(this, "", title, "", 200, tempPair);
//
//        HashMap<String, String> map = new HashMap<>();
//        for (Pair<String, String> p : pairs) {
//            map.put(p.first, p.second);
//        }
//        isLoadDetail = true;
////        SkipUtil.skipWithNewsItem(this, item, map);
//        Intent intent = new Intent(this, NewesDetailActivity.class);
//        intent.putExtra(BaseActivity.EX_URL, item.getNewsUrl());
//        intent.putExtra("TAG", map);
//
//        startActivityForResult(intent, INTO_NEWSINFO);
    }

    /**
     * 滑动到指定位置
     */
    private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
        JLog.e("OnItemClick---", "smoothMoveToPosition  position = " + position);
        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));
        if (position < firstItem) {
            // 第一种可能:跳转位置在第一个可见位置之前
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            // 第二种可能:跳转位置在第一个可见位置之后
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                mRecyclerView.smoothScrollBy(0, top);
            }
        } else {
            // 第三种可能:跳转位置在最后可见项之后
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == INTO_NEWSINFO) {
                NewsItem item = newsList.get(selectedToInfoIndex);
                boolean isDigg = data.getBooleanExtra(INTO_NEWSINFO_ISDIGG, false);
                if (isDigg != item.isDigg()) {
                    RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                    View lastView = manager.findViewByPosition(selectedToInfoIndex);
                    VideoPlayHolder lastHolder = null;
                    if (null != lastView) {
                        lastHolder = (VideoPlayHolder) recyclerView.getChildViewHolder(lastView);
                    }
                    if (isDigg) {
                        newsList.get(selectedToInfoIndex).setCountDigg(item.getCountDigg() + 1);
                        if (null != lastHolder) {
                            Drawable drawable = VideoPlayViewActivity.this.getResources().getDrawable(R.mipmap.icon_compere_btn_press);
                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                            lastHolder.doUp.setDrawables(drawable, null, null, null);
                            lastHolder.doUp.setTextColor(VideoPlayViewActivity.this.getResources().getColor(R.color.colorTxRedMain_));
                            lastHolder.doUp.setText("" + newsList.get(selectedToInfoIndex).getCountDigg());
                        }
                    } else {
                        newsList.get(selectedToInfoIndex).setCountDigg(item.getCountDigg() - 1);
                        if (null != lastHolder) {
                            Drawable drawable = VideoPlayViewActivity.this.getResources().getDrawable(R.mipmap.icon_compere_btn_white);
                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                            lastHolder.doUp.setDrawables(drawable, null, null, null);
                            lastHolder.doUp.setTextColor(VideoPlayViewActivity.this.getResources().getColor(R.color.colorOpinionSelectNo));
                            lastHolder.doUp.setText("" + newsList.get(selectedToInfoIndex).getCountDigg());
                        }
                    }
                    newsList.get(selectedToInfoIndex).setDigg(isDigg);
                    adapter.updateData(newsList);
                }
            }
        }
    }


}
